/**
 * Created by Toma on 2016-6-22 10:58:08
 * 月子中心
 */
var fn = {};

/**
 * 1.上传小票页面
 */
fn.start = function () {
  // 设置选择时间插件
  $('#datetime').mdater({
    minDate: new Date(2015, 6, 13)
  });

  // 选择卖场
  stores.init();

  // 上传图片 提交表单
  var imageload = new ImageUpload(option);
  // imageload.init();
  // 测试
  imageload.test();
};

/**
 * 2.小票状态
 */
fn.check = function () {
  // 进度条
  var _point = $('.point'),
      size = _point.data('size');
  _point.css('left',size);
  $('.timeline .before').width(size);
  
  // 审核状态
  var page = $('body').data('page'),
      _ctit = $('.c-tit'),
      _wite = $('.lin-wite');
  if(page == 1){
    _ctit.removeClass('sccg').addClass('shcg');
    _wite.remove();
    $('.stu1').show().siblings('.info').hide();
  }else if(page == 2){
    _ctit.removeClass('sccg').addClass('shsb');
    _wite.remove();
    $('.stu2').show().siblings('.info').hide();
    $('#showsub').show();

    upimg();
  }

  // 分享
  $('.share').tap(function () {
    $(this).hide();
  });

  // 上传图片
  function upimg() {
    $('#showsub').tap(function () {
      $('.pop-in').show();
    });
    $('.pop-mask').tap(function () {
      $('.pop-in').hide();
    });

    var imageload = new ImageUpload(option1);
    // imageload.init();
    // 测试
    imageload.test();
  }
};



/**
 * 选择卖场
 */
var stores = {
  storebox: $('.stores'),
  storecrl: $('#stores'),
  show: function () {
    stores.storebox.show();
    $('body,html').addClass('ovfHiden');
  },
  hideen: function () {
    stores.storebox.hide();
    $('body,html').removeClass('ovfHiden');
  },
  layer: function () {
    var bg = $(this).children('img').attr('src'),
        val = $(this).children('span').text();
    stores.storecrl.val(val).addClass('bg-item').css({'background-image': 'url(' + bg + ')'});
    stores.hideen();
  },
  init: function () {
    var _this = this;
    $(_this.storecrl).on('tap', _this.show);
    $('.stores-mask').on('tap', _this.hideen);
    $('.st-ul').on('tap', '.layer', _this.layer);
  }
};

/**
 * option 上传小票默认设置
 */
var option = {
  // 测试上传图片的地址
  test: '../php/com.php',
  // 表单提交地址
  url: '../php/user.php',

  images: [], // 保存上传的图片url
  addbtn: '', // 保存上传按钮状态

  imgbtn: $('.addbtn'), // 上传图片的按钮
  subbtn: $('#sub'), // 提交表单按钮


  // 显示当前状态
  status: function (data) {
    layer.open({
      content: data,
      style: 'background-color:#00b0af; color:#fff;',
      time: 4
    });
  },
  imgbeforeSend: function () {
    layer.open({
      content: '<i class="loading"></i>小票飞速上传中...',
      style: 'background-color:#00b0af; color:#fff;',
      shadeClose: false
    });
  },
  imgsuccess: function () {
    layer.close(0);
    this.status('上传成功');
    $(this.addbtn).off('tap');
  },
  imgerr: function () {
    this.status('上传图片失败');
  },
  case: function () {
    var stores = $.trim($('#stores').val()),
        dnum = $.trim($('#dnum').val()),
        cnum = $.trim($('#cnum').val()),
        datetime = $.trim($('#datetime').val());
    if (stores && datetime && this.images.length) {
      return {
        stores: stores,
        datetime: datetime,
        dnum: dnum,
        cnum: cnum,
        images: this.images
      };
    } else {
      this.status('请将数据填写完整');
      return false;
    }
  },
  formbeforeSend: function (e) {
    this.status('<i class="loading"></i>表单提交中');
  },
  formsuccess: function (e) {
    window.location.href = 'check.html';
  }
};

// 重新上传小票
var option1 = {
  // 测试上传图片的地址
  test: '../php/com.php',
  // 表单提交地址
  url: '../php/user.php',

  images: [], // 保存上传的图片url
  addbtn: '', // 保存上传按钮状态
  imgbtn: $('.addbtn'), // 上传图片的按钮
  subbtn: $('#sub'), // 提交表单按钮

  // 显示当前状态
  status: function (data) {
    layer.open({
      content: data,
      style: 'background-color:#00b0af; color:#fff;',
      time: 4
    });
  },
  imgbeforeSend: function () {
    layer.open({
      content: '<i class="loading"></i>小票飞速上传中...',
      style: 'background-color:#00b0af; color:#fff;',
      shadeClose: false
    });
  },
  imgsuccess: function () {
    layer.close(0);
    this.status('上传成功');
    $(this.addbtn).off('tap');
  },
  imgerr: function () {
    this.status('上传图片失败');
  },
  case: function () {
    if (this.images.length) {
      return {
        images: this.images
      };
    } else {
      this.status('请上传图片');
      return false;
    }
  },
  formbeforeSend: function (e) {
    this.status('<i class="loading"></i>表单提交中');
  },
  formsuccess: function (e) {
    window.location.href = 'check.html';
  }
};


/**
 * 上传图片，提交表单，模拟微信上传图片
 * @constructor
 *
 */
function ImageUpload(option) {
  this.option = option;
  // 多图上传时保留的上一张图片名 避免重复上传
  this.lastimg = '';
}

/**
 * 1.初始化默认调用方法。
 */
ImageUpload.prototype.init = function () {
  var that = this;
  that.event();
  that.option.imgbtn.on('tap', function (e) {
    that.wxImg(that);
    that.option.addbtn = e.target;
  });
};

/**
 * 2.测试时调用方法
 */
ImageUpload.prototype.test = function () {
  var that = this;
  that.event();
  that.testInit();
  that.option.imgbtn.on('tap', function (e) {
    that.testImg(e, that);
    that.option.addbtn = e.target;
  });
};

/**
 * 3.用户行为 初始化操作
 */
ImageUpload.prototype.event = function () {
  var that = this;
  // 提交按钮
  $(that.option.subbtn).tap(function (e) {
    e.preventDefault();
    that.sub(e, that);
  });
};


/**
 * 5.提交表单
 * @param e
 * @param that
 */
ImageUpload.prototype.sub = function (e, that) {
  var data = that.option.case();
  if (data) {
    $.ajax({
      url: that.option.url,
      type: 'post',
      data: data,
      beforeSend: function () {
        e.target.disabled = true;
        that.option.formbeforeSend(e);
      },
      success: function (data) {
        e.target.disabled = false;
        that.option.formsuccess(e);
      },
      error: function () {
        e.target.disabled = false;
        that.option.status('上传图片失败');
      }
    });
  }
};

/**
 * 6.微信上传
 * @param e
 * @param that
 */
ImageUpload.prototype.wxImg = function (that) {
  // 调用微信图片接口
  wx.chooseImage({
    count: 9, // imgCount
    sizeType: ['compressed'],
    sourceType: ['camera'],
    success: function (res) {
      that.option.imgbeforeSend();
      wxUpload(res.localId);
    }
  });
  // 上传图片
  function wxUpload(id) {
    wx.uploadImage({
      localId: id, // 需要上传的图片的本地ID，由chooseImage接口获得
      isShowProgressTips: 1, // 默认为1，显示进度提示
      success: function (res) {
        var serverId = res.serverId; // 返回图片的服务器端ID
        $.getJSON("http://www.vdui.cn/bbsdw/uploadImg", {"mediaId": serverId}, function (data) {
          if (data.errcode == 0) {
            that.addImage(data.url, that);
          } else {
            that.option.imgerr();
          }
        });
      },
      fail: function (res) {
        alert(JSON.stringify(res));
        that.option.imgerr();
      }
    });
  }
};

/**
 * 7.模拟微信上传 初始化时添加iframe组件
 */
ImageUpload.prototype.testInit = function () {

  var tmp = document.createElement('iframe');
  tmp.id = 'tmpIframe';
  tmp.name = 'tmpIframe';
  tmp.style.display = 'none';
  document.body.appendChild(tmp);

  var form = document.createElement('form');
  form.id = 'tmpFileForm';
  form.action = this.option.test;
  form.method = "post";
  form.target = "tmpIframe";
  form.enctype = "multipart/form-data";
  form.style.display = 'none';
  document.body.appendChild(form);

  var azFile = document.createElement("input");
  azFile.name = "azFile";
  azFile.id = "azFile";
  azFile.type = "file";
  document.getElementById("tmpFileForm").appendChild(azFile);
};

/**
 * 8.模拟微信上传
 * @param e
 * @param that
 */
ImageUpload.prototype.testImg = function (e, that) {
  var file = $('#azFile'),
      fet = false; // 禁止反复触发change

  file.trigger('click');
  file.on('change', function () {
    if (file.val() != that.lastimg && file.val()) {
      $("#tmpFileForm").submit();
      that.option.imgbeforeSend();
      that.lastimg = file.val();
      fet = true;
    }
  });

  $('#tmpIframe').on('load', function () {
    /**
     * 获取返回的数据
     * @type {*|jQuery}
     */
    var data = $.trim($(window.frames['tmpIframe'].document.body).find('p').html());
    if (fet) data ? that.addImage(data, that) : that.option.imgerr();
    $(e.target).css({'background': 'url(' + window.URL.createObjectURL(file.get(0).files[0]) + ') center/cover'});
  });
};

/**
 * 9.将返回图片的地址添加到images中,并判断图片上传的张数
 * @param data 图片地址
 * @param e
 * @param that
 */
ImageUpload.prototype.addImage = function (data, that) {
  that.option.images.push(data);
  that.option.imgsuccess();
};

